<?php

ignore_user_abort(true); 				// 后台运行，不受前端断开连接影响
set_time_limit(0);
ini_set('max_execution_time', '0');
chdir(dirname(__FILE__));
error_reporting(E_ERROR);
require_once ("../log.php");
require_once ("../config.php");			// 引入配置ss
require_once ("../api/api_tool.php");

/**
 * @name Api接口demo（php版）
 * @desc 本接口列表，只是用于系统处理机器人行为
 * 一分钟执行一次，给符合条件的机器人发送
 */

// 当前时间
$nowdate = simQuery("SELECT NOW() AS nowdate")['nowdate'];

// 截取出当前的时和分
$hm_time = substr($nowdate, 11, 5);

// 更新有效期机器人的时间列表
simQuery("UPDATE robot AS bot, wechat_group AS wx SET wx.wait_time = wx.wait_time + 1 WHERE ".
	"bot.service_period > '{$nowdate}' AND ".		// 是否过期
	"wx.start_time < '{$hm_time}' AND ".			// 是否在发单时间内
	"wx.finish_time > '{$hm_time}' AND ".			
	"wx.status = 1 AND ".							// 是否开启发单
	"wx.robot_wxid = bot.wechat_id;"				// 关联查询
);

$bot_list = AllQuery("SELECT wx.id AS wx_id, bot.id AS bot_id, bot.server_id AS bot_server, bot.channel AS bot_channel, ".
	"ser.host AS host, ser.port AS port FROM robot AS bot, wechat_group AS wx, `server` AS ser WHERE ".
	"bot.channel <> '' AND ".													// 是否有选择发单
	"(CAST(wx.wait_time AS signed) - CAST(wx.interval AS signed)) >= 0 AND ".	// 是否到发单时间
	"bot.service_period > '{$nowdate}' AND ".									// 是否过期
	"wx.start_time < '{$hm_time}' AND ".										// 是否在发单时间内
	"wx.finish_time > '{$hm_time}' AND ".
	"wx.status = 1 AND ".														// 用户是否开启发单
	"wx.robot_wxid = bot.wechat_id AND ".										// 关联查询
	"bot.server_id = ser.id"
);

$send_bot_list = array();
if (!empty($bot_list)) {
	// 获取操作地址
	for ($i = 0; $i < count($bot_list); ++$i) {
		$bot = $bot_list[$i];
		if (empty($send_bot_list[$bot['bot_id']])) {
			$send_bot_list[$bot['bot_id']] = true;
			$host = $bot['host'];
			$port = $bot['port'];
			$ch_list = explode(',', $bot['bot_channel']);
			$ch_value = $ch_list[array_rand($ch_list, 1)]; 	// 获取一个随机值
			$data = array (
				'wx_id'			=> $bot['wx_id'],
				'bot_id' 		=> $bot['bot_id'],
				'channel_id'	=> $ch_value,
				'fun'			=> 'select_fit_shop',
			);
			$data['sign'] = generateSign($data);

			$url = '/api/api_accept_post.php';
			sendFZSHttp($host, $port, $url, $data);
		}
	}
}

exit();

// 分析整点时需要给所有正在工作的机器人
// $nowdate

?>